<template>
  <view class="mobile-item-container">
    <!-- 中间区域 -->
    <view class="music-container">
      <!-- 中心圆形区域 -->
      <view class="center-circle">
        <!-- 修改图片地址为封面图片 -->
        <image :src="coverUrl || '/static/img/music/music.jpg'" class="center-icon" :class="{ 'rotate': isPlaying }"></image>
      </view>
    </view>
    <!-- 播放中状态 -->
    <view v-if="isMonitoring" class="monitoring-tip" style="flex: 3;">当前为监测状态，不可预览音乐</view>
    <view v-if="!isMonitoring" class="play-status">
      <!-- 第一行：音乐名称和收藏按钮 -->
      <view style="display: flex;  flex: 2;" >
        <!-- 使用自定义组件替代 up-notice-bar -->
        <NoticeBar
          v-if="musicList.length > 0 && currentIndex < musicList.length"
          :text="` ${musicList[currentIndex].name}`"
          :speed="isPlaying ? 60 : 0"
          :width="400"
          :textHeight="100" 
          :fontSize="80" 
        ></NoticeBar>
        <!-- 占位组件 -->
        <view style="flex: 2;"></view>
        <!-- 收藏按钮 -->
        <view @click="collect" style="flex: 1; display: flex;">
          <up-icon :name="musicList.length > 0 && currentIndex < musicList.length && musicList[currentIndex].isCollected === 1 ? `heart-fill` : `heart`" size="30" 
          :color="musicList.length > 0 && currentIndex < musicList.length && musicList[currentIndex].isCollected === 1 ? `#ee0000` : `#398ade`"></up-icon>
        </view>
      </view>
      <!-- 第二行：歌手和专辑 -->
      <view style="display: flex; flex: 1.5;">
        <up-text 
        type="primary"
          v-if="musicList.length > 0 && currentIndex < musicList.length"
          :text="`歌手: ${musicList[currentIndex].singer}`"
          :size="20"
        ></up-text>
      </view>
      <view style="display: flex; flex: 1;">
        <up-text 
          type="info"  :lines="1"
          v-if="musicList.length > 0 && currentIndex < musicList.length"
          :text="`专辑: ${musicList[currentIndex].album}`"
          :size="20"
        ></up-text>
      </view>
      <!-- 第三行：所属分类 -->
      <view style="display: flex; flex: 1; ">
       <up-tag 
          type="success"
          icon="tags-fill"
          v-if="musicList.length > 0 && currentIndex < musicList.length"
          :text="` ${title}`"
          size="large"
        ></up-tag>
      </view>
    </view>

    <!-- 底部控制栏（上一首、播放暂停、下一首） -->
    <view v-if="!isMonitoring"  class="music-controls">
      <view class="control-button" @click="prevMusic">
        <up-icon :name="`arrow-left`" size="30" color="#398ade" ></up-icon>
      </view>
      <view class="play-button" @click="togglePlay">
        <up-icon :name="isPlaying? `pause`:`play-circle`" size="40" color="#398ade"></up-icon>
      </view>
      <view class="control-button" @click="nextMusic">
        <up-icon :name="`arrow-right`" size="30" color="#398ade" ></up-icon>
      </view>
    </view>

  </view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app';
import { getMusicList } from '@/api/music'; // 引入接口请求方法
import { ref, computed } from 'vue';
import { useStore } from 'vuex';
// 引入自定义组件
import NoticeBar from '@/components/NoticeBar.vue';
// 引入 toast
// @ts-ignore
import { toast } from '@/uni_modules/uview-plus';
import { toggleCollect } from '@/api/music'; // 引入收藏接口

const store = useStore();

import type { MusicItem } from '@/types/music';

const coverUrl = ref<string>('');
const title = ref<string>('');
const isMonitoring = computed({
  get(): boolean {
    // 兜底默认值：若 store 中未初始化，默认 false
    return store.state.music.isMonitoring ?? false; 
  },
  set(newValue: boolean) {
    // 此页面不要使用
    store.dispatch('updateIsMonitoring', newValue);
  }
});

const musicList = computed<MusicItem[]>({
  get(): any[] {
    // 双重兜底：先判断 isMonitoring，再处理 musicList 可能的 undefined
    return !store.state.music.isMonitoring 
      ? (store.state.music.musicList || []) // store.state.music.musicList 为 undefined 时默认空数组
      : [];
  },
  set(newValue: any[]) {
    if (!store.state.music.isMonitoring) {
		console.log("?musicList.set",newValue)
      store.dispatch('updateMusicList', newValue);
    } else {
      console.log("当前为监测状态，不可预览音乐");
    }
  }
});

const currentIndex = computed<number>({
  get(): number {
    // 兜底默认值：若 store.state.music.currentIndex 未定义，默认 0
    return !store.state.music.isMonitoring 
      ? (store.state.music.currentIndex || 0) 
      : 0;
  },
  set(newValue: number) {
    if (!store.state.music.isMonitoring) {
      store.dispatch('updateCurrentIndex', newValue);
    } else {
      console.log("当前为监测状态，不可预览音乐");
    }
  }
});

const isPlaying = computed<boolean>({
  get(): boolean {
    // 兜底默认值：若 store.state.music.isPlaying 未定义，默认 false
    return !store.state.music.isMonitoring 
      ? (store.state.music.isPlaying || false) 
      : false;
  },
  set(newValue: boolean) {
    if (!store.state.music.isMonitoring) {
      store.dispatch('updateIsPlaying', newValue);

    } else {
      console.log("当前为监测状态，不可预览音乐");
    }
  }
});

const togglePlay = () => {
  isPlaying.value = !isPlaying.value;
   // #ifndef H5
   if (isPlaying.value===true) {
		  console.log("设置背景音频自然播放结束事");
        const audio = uni.getBackgroundAudioManager();
        audio.onEnded(() => {
			console.log("背景音频自然播放结束事件触发");
			store.dispatch('handleAudioEnded');
        });
        }
      // #endif
};

const prevMusic = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
    coverUrl.value = musicList.value[currentIndex.value].cover;
  } else {
    // 提示没有上一首
    toast('没有上一首');
  }
};

const collect = async () => {
  try {
    const currentMusic = musicList.value[currentIndex.value] as MusicItem; // 明确类型
    await toggleCollect(currentMusic.id); // 调用收藏接口
    // 更新音乐的收藏状态
    currentMusic.isCollected = currentMusic.isCollected === 0 ? 1 : 0;
    console.log("收藏状态已更新");
  } catch (error) {
    console.error('收藏音乐失败:', error);
  }
};

const nextMusic = () => {
  if (currentIndex.value < musicList.value.length - 1) {
    currentIndex.value++;
    coverUrl.value = musicList.value[currentIndex.value].cover;
  } else {
    // 提示没有下一首
    toast('没有下一首');
  }
};

const fetchMusicInfo = async (id: number, title: string) => {
  try {
    const response = await getMusicList(title); // 调用接口获取音乐数据
    // @ts-ignore
    const musicListData = response.data;
    // @ts-ignore
    musicList.value = musicListData.map((music: any) => {
      return {
        id: music.musicId,
        name: music.name,
        singer: music.singer,
        album: music.album,
        url: `${process.env.BASE_URL}${music.url}`,
        cover: `${process.env.BASE_URL}${music.cover}`,
        duration: music.duration,
        isCollected : music.isCollected
      } as MusicItem; // 明确类型
    });
    // 获取符合条件的元素的下标
    const index = musicList.value.findIndex((item: any) => item.id === id)
    if (index !== -1) {
      const musicInfo = musicList.value[index];
      coverUrl.value = musicInfo.cover;
      // 更新当前播放的音乐索引
      currentIndex.value = index;
    }
	isPlaying.value=true;
  } catch (error) {
     console.error('音乐数据获取失败:', error);
  }
};

onLoad((options: any) => {
  const id = parseInt(options.id);
  title.value = options.title;
  fetchMusicInfo(id, options.title);
});
</script>

<style lang="scss" scoped>
/* 页面样式 */
.mobile-item-container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(to bottom, #a5d8f3, #c7e6f5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: start;
  padding: 20rpx 0;
}

/* 音乐播放区域 */
.music-container {
  position: relative;
  margin-top: 100rpx;
  width: 80%;
  height: 30%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 可根据需求调整父容器样式 */
.parent-container {
  overflow: hidden; /* 确保滚动效果正常显示 */
  line-height: 50rpx; /* 让行高等于容器高度 */
  text-align: center; /* 如果还需要水平居中，可添加此属性 */
}

/* 中心圆形 */
.center-circle {
  width: 320rpx;
  height: 320rpx;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0rpx 40rpx 100rpx rgba(0, 0, 0, 0.2);
}

.center-icon {
  width: 200rpx;
  height: 200rpx;
  transition: transform 1s linear; // 添加过渡效果
  border-radius: 50%;
}

/* 旋转动画 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 旋转类 */
.rotate {
  animation: rotate 10s linear infinite; // 每10秒旋转一圈
}


/* 底部音乐控制栏（3 个按钮） */
.music-controls {
  margin-top: 15%;
  width: 70%;
  max-width: 70%;
  height: 15%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10rpx 20rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 30rpx;
  box-shadow: 0rpx -20rpx 80rpx rgba(0, 0, 0, 0.1);
}

/* 控制按钮（上一曲/下一曲，圆形样式） */
.control-button {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0rpx 30rpx 60rpx rgba(0, 0, 0, 0.2);
}

/* 底部按钮图标 */
.control-icon {
    width: 120rpx;
    height: 120rpx;
}

/* 播放/暂停按钮 */
.play-button {
    
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0rpx 30rpx 60rpx rgba(0, 0, 0, 0.2);
}

.play-icon {
  width: 35rpx;
  height: 35rpx;
}

/* 修改：添加样式类 */
.play-status {
  height: 25%;
  width: 80%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: space-between;
}
/* 添加提示区域样式 */
.monitoring-tip {
  color: red;
  font-size: 40rpx;
  margin-top: 20rpx;
  text-align: center;
}
</style>